local log = require "modules.commhm.log"
local mis_log = require "mis_log"
local mis_config = require "mis_config"
local t_retCode = mis_config.t_retCode
local mis_data = require "mis_data"
local mis_bridge = require "mis_bridge"
local uu = require "modules.commhm.utils"
local mis_tools = require "mis_tools"
local os              = os
local tonumber        = tonumber
local M = {}
local mis_common = require "mis_common"

local LOG_NAME = "mis_moon"

M.reset_moon_data = function ()
    local ok, moon_data = mis_data.get_user():get_moon_data()
    if ok~=t_retCode.n_OK then
        return t_retCode.n_SYS_ERR, 'ssdb error'
    end
    local ok2, code = mis_data.get_user():set_moon_data(nil)
    return t_retCode.n_OK
end

M.add_total_score = function ()
    local cake =  tonumber(ngx.ctx.m_params.cake)

    local ok, moon_data = mis_data.get_user():get_moon_data()
    if ok~=t_retCode.n_OK then
        return t_retCode.n_SYS_ERR, 'ssdb error'
    end

    if not moon_data then 
        return t_retCode.n_SYS_ERR, 'param error'
    end

    moon_data.total_score = moon_data.total_score + tonumber(cake)

    local ok2, code = mis_data.get_user():set_moon_data(moon_data)
    return t_retCode.n_OK
end

local new_home_page_data = function ()
    local home_page_data = {}
    home_page_data.location_status = {0, 0, 0, 0, 0, 0, 0, 0, 0}
    home_page_data.rewards_status = {0, 0, 0, 0, 0, 0, 0}
    home_page_data.round = 1
    home_page_data.select_rewards_id = nil
    home_page_data.select_rewards_status = mis_tools.REWARDS_STATUS.NONE

    return home_page_data
end

--皓月圆梦首页
--参数： 无
--返回值： 
    --total_score 月饼总余额
    --location_status 九宫格点亮信息 0没亮 1点亮
    --rewards_status 奖励完成信息 0不可领取 1可领取 2已领取
    --round 轮数 
    --select_rewards_status 自选大奖状态信息 0不可领取 1可领取 2已领取
    --select_rewards 自选大奖品详细信息({}空table代表没有)
M.moon_home_page = function ()
    local uin =  tonumber(ngx.ctx.m_params.uin)
    local t_moonConf 	= mis_data.t_moon.t_conf 
    --log.debug("t_moonConf="..uu.to_str(t_moonConf))

    if (not uin)
    or (not t_moonConf) 
    or (not t_moonConf.wishing_cfg) 
    or (not t_moonConf.wishing_cfg.select_list) then 
        return t_retCode.n_PARAM_ERR, 'param error'
    end

    local ok, moon_data = mis_data.get_user():get_moon_data()
    if ok~=t_retCode.n_OK then
        return t_retCode.n_SYS_ERR, 'ssdb error'
    end
    
    local b_update = false
    if not moon_data then 
        moon_data = {}
        moon_data.total_score = 0
        moon_data.home_page_data = new_home_page_data()
        b_update = true
    end
    if (not moon_data.home_page_data) 
    or (not moon_data.home_page_data.location_status) 
    or (not moon_data.home_page_data.rewards_status)
    or (not moon_data.home_page_data.round)
    or (not moon_data.home_page_data.select_rewards_status) then 
        moon_data.total_score = 0
        moon_data.home_page_data = new_home_page_data()
        b_update = true
    end

    if not moon_data.total_score then 
        moon_data.total_score = 0
        b_update = true
    end

    if b_update then
        local n_code, n_desc = mis_data.get_user():set_moon_data(moon_data)
        if n_code ~= t_retCode.n_OK then
            log.day_list(LOG_NAME, "[ERROR] moon_home_page", "set_moon_data error!", "uin="..uin)
            return n_code, n_desc
        end
    end

    local t_ret = {}
    t_ret.total_score = moon_data.total_score or 0
    t_ret.location_status = moon_data.home_page_data.location_status
    t_ret.rewards_status = moon_data.home_page_data.rewards_status
    t_ret.round = moon_data.home_page_data.round
    t_ret.select_rewards_status = moon_data.home_page_data.select_rewards_status
    t_ret.already_select_items = moon_data.already_select_items
    t_ret.select_rewards = {}
    if moon_data.home_page_data.select_rewards_id then 
        local select_id = tonumber(moon_data.home_page_data.select_rewards_id)
        if t_moonConf.wishing_cfg.select_list[select_id] then 
            t_ret.select_rewards.awardId  = t_moonConf.wishing_cfg.select_list[select_id].awardId
            t_ret.select_rewards.awardNum  = t_moonConf.wishing_cfg.select_list[select_id].awardNum
            t_ret.select_rewards.awardRound  = t_moonConf.wishing_cfg.select_list[select_id].awardRound
        end
    end
    
    return  t_retCode.n_OK, t_ret
end

local calc_light_rewards = function (t_location_status, t_rewards_status)
    --固定9宫格， 只有7个奖励，穷举了拉倒
    local new_light_t = {}
    --1
    if (t_rewards_status[1]==0) and (t_location_status[1]==1) and (t_location_status[4]==1) and (t_location_status[7]==1) then 
        table.insert(new_light_t, 1)
    end
    --2
    if (t_rewards_status[2]==0) and (t_location_status[2]==1) and (t_location_status[5]==1) and (t_location_status[8]==1) then 
        table.insert(new_light_t, 2)
    end
    --3
    if (t_rewards_status[3]==0) and (t_location_status[3]==1) and (t_location_status[6]==1) and (t_location_status[9]==1) then 
        table.insert(new_light_t, 3)
    end
    --4
    if (t_rewards_status[4]==0) and (t_location_status[3]==1) and (t_location_status[5]==1) and (t_location_status[7]==1) then 
        table.insert(new_light_t, 4)
    end
    --5
    if (t_rewards_status[5]==0) and (t_location_status[1]==1) and (t_location_status[2]==1) and (t_location_status[3]==1) then 
        table.insert(new_light_t, 5)
    end
    --6
    if (t_rewards_status[6]==0) and (t_location_status[4]==1) and (t_location_status[5]==1) and (t_location_status[6]==1) then 
        table.insert(new_light_t, 6)
    end
    --7
    if (t_rewards_status[7]==0) and (t_location_status[7]==1) and (t_location_status[8]==1) and (t_location_status[9]==1) then 
        table.insert(new_light_t, 7)
    end

    return new_light_t
end

--点亮拼图
--参数： 无
--返回值： 
    --location_status 九宫格点亮信息 0没亮 1点亮
    --rewards_status 奖励完成信息 0不可领取 1可领取 2已领取
    --rewards 本次点亮获取的奖励信息 {}空table代表没有
    --select_rewards_status 自选大奖状态信息 0不可领取 1可领取 2已领取
    --total_score 月饼总余额
    --select_ids本次点亮的区域
--[[
--奖励依次为:
    1   2   3   4
                5
                6
                7
--格子依次为:
    1   2   3
    4   5   6
    7   8   9
--]]
M.moon_light_up = function ()
    --log.debug("t_moonConf="..uu.to_str(t_moonConf))
    local uin =  tonumber(ngx.ctx.m_params.uin)
    local apiid = tonumber(ngx.ctx.m_params.apiid)

    local t_moonConf = mis_data.t_moon.t_conf 
    if not uin or not apiid or (not t_moonConf)
    or (not t_moonConf.wishing_cfg)
    or (not t_moonConf.wishing_cfg.min_baoji_pro)
    or (not t_moonConf.wishing_cfg.max_baoji_pro)
    or (not tonumber(t_moonConf.wishing_cfg.min_baoji_pro))
    or (not tonumber(t_moonConf.wishing_cfg.max_baoji_pro)) then 
        return t_retCode.n_PARAM_ERR, 'param error'
    end
    
    local min_baoji_pro = tonumber(t_moonConf.wishing_cfg.min_baoji_pro)
    local max_baoji_pro = tonumber(t_moonConf.wishing_cfg.max_baoji_pro)

    local ok, moon_data = mis_data.get_user():get_moon_data()
    if ok~=t_retCode.n_OK then
        return t_retCode.n_SYS_ERR, 'ssdb error'
    end

    if (not moon_data) 
    or (not moon_data.home_page_data) 
    or (not moon_data.home_page_data.location_status)  
    or (not moon_data.home_page_data.rewards_status) then 
        return t_retCode.n_WORK_ERR, '[ERROR] moon_light_up no moon_data!'
    end

    if moon_data.total_score<=0 then
        return t_retCode.n_WORK_ERR, '[ERROR] moon_light_up total_score <= 0!'
    end

    moon_data.total_score = moon_data.total_score - 1

    local light_count = 1
    local random_num = math.random(1, 100)
    if random_num <= min_baoji_pro then 
        light_count = 2
    end
    if random_num <= max_baoji_pro then 
        light_count = 3
    end

    --找出还未点亮的区域ID
    local not_light_t = {}
    local location_status = moon_data.home_page_data.location_status
    for k, v in pairs(location_status) do 
        if v==0 then 
            table.insert(not_light_t, k)
        end
    end

    --本次点亮区域的ID
    local select_t = {}
    local light_rewards_t = {}
    for i=1, light_count do
        if #not_light_t==0 then 
            break
        end
        local select_id = math.random(1, #not_light_t)
        table.insert(select_t, not_light_t[select_id])
        table.remove(not_light_t, select_id)

        if moon_data.home_page_data.location_status[select_t[#select_t]]~=0 then 
            log.day_list(LOG_NAME, "[ERROR] moon_light_up", "select_id error!", "uin="..uin)
            return t_retCode.n_SYS_ERR, 'select_id error'
        end
        moon_data.home_page_data.location_status[select_t[#select_t]] = 1

        local new_light_t = calc_light_rewards(moon_data.home_page_data.location_status, moon_data.home_page_data.rewards_status)
        if #new_light_t>0 then 
            for _, v in pairs(new_light_t) do
                --这里需要自动领取
                moon_data.home_page_data.rewards_status[v] = mis_tools.REWARDS_STATUS.ALREADY
                table.insert(light_rewards_t, t_moonConf.wishing_cfg.lighten_list[v])
            end

            --遍历一下，看看是不是九宫格都打开并产生自选大奖了
            local no_lighten_flag = false 
            for _, v in pairs(moon_data.home_page_data.rewards_status) do
                if v==0 then 
                    no_lighten_flag = true
                end
            end
            --没有不亮的了就置位自选大奖标志位
            if not no_lighten_flag then 
                moon_data.home_page_data.select_rewards_status = mis_tools.REWARDS_STATUS.READY
                --update_task
                if not moon_data.task_data then 
                    moon_data.task_data = {}
                end
                mis_tools.update_task(1003, 1, moon_data.task_data, t_moonConf.task_cfg)
            end
        end
    end

    --select_t是本次点亮图标的数组
    if #select_t==0 then 
        log.day_list(LOG_NAME, "[ERROR] moon_light_up", "select_t error!", "uin="..uin)
        return t_retCode.n_SYS_ERR, 'no light_up'
    end

    --发给账号服需要这种结构
    local send_rewards = {}
    for _, v in pairs(light_rewards_t) do
        local one_reward = {}
        one_reward.id  = tonumber(v.awardId)
        one_reward.num  = tonumber(v.awardNum)
        table.insert(send_rewards, one_reward)
    end 
    --账号服发奖
    if #send_rewards>0 then
        --账号服发奖
        local ok2, reason_1, s_items, s_reason = mis_bridge.add_items(uin, send_rewards, "mis_sanrio", "mis_sanrio_add_item")
        if ok2~=t_retCode.n_OK then 
            log.day_list(LOG_NAME, '[ERROR] moon_light_up call accout error!', "uin="..uin, "apiid="..apiid, "send_rewards="..uu.to_str(send_rewards)
                ,"accout_ret="..uu.to_str(ok2), "reason_1="..reason_1, "s_items="..uu.to_str(s_items), "s_reason="..s_reason)
            return t_retCode.n_SYS_ERR, "call account add_items error!"
        end
        --埋点数据
        mis_log.remote_pure_day("autumnfestival_receive", mis_common.table_to_json({
            ip = ngx.ctx.m_params.s_remoteAddr or ngx.ctx.xff or ngx.var.remote_addr or "nil",
            uin = uin,
            time = ngx.ctx.m_params.createTime or uu.now(),
            country = ngx.ctx.m_params.country or 'nil',
            apiid = ngx.ctx.m_params.apiid or 'nil',
            ver = ngx.ctx.m_params.ver or 'nil',
            lang = ngx.ctx.m_params.lang or 'nil',

            key = 'getaward',
            type = "autumnfestival_receive",
            bonus = send_rewards,
        }))
    end 

    local n_code, _desc = mis_data.get_user():set_moon_data(moon_data)
    if n_code ~= t_retCode.n_OK then
        log.day_list(LOG_NAME, "[ERROR] moon_light_up", "set_moon_data error!", "uin="..uin)
        return n_code, _desc
    end

    local t_ret = {}
    t_ret.location_status = moon_data.home_page_data.location_status
    t_ret.rewards_status =  moon_data.home_page_data.rewards_status
    t_ret.rewards = light_rewards_t
    t_ret.select_rewards_status = moon_data.home_page_data.select_rewards_status
    t_ret.total_score = moon_data.total_score or 0
    t_ret.select_ids = select_t

    --日志记录可领奖时的点亮操作
    if #light_rewards_t>0 then 
        log.day_list(LOG_NAME, '[INFO] moon_light_up ok', 'uin='..uin, "apiids="..apiid, "total_score=".. t_ret.total_score 
            , "select_ids="..uu.to_str(t_ret.select_ids), "select_rewards_status="..uu.to_str(t_ret.select_rewards_status)
            , "rewards="..uu.to_str(t_ret.rewards), "location_status="..uu.to_str(t_ret.location_status)
            , "rewards_status="..uu.to_str(t_ret.rewards_status)
        )
    end 

    return  t_retCode.n_OK, t_ret
end

--设置自选大奖
--参数： 
    --select_id 设置的奖励配置ID 
--返回值： 
   --成功：0   失败：非0
M.moon_set_select_rewards = function ()
    local uin =  tonumber(ngx.ctx.m_params.uin)
    local select_id = tonumber(ngx.ctx.m_params.select_id)
    if (not uin) or (not select_id) then 
        return t_retCode.n_PARAM_ERR, 'param error'
    end

    local ok, moon_data = mis_data.get_user():get_moon_data()
    if ok~=t_retCode.n_OK then
        return t_retCode.n_SYS_ERR, 'ssdb error'
    end

    if (not moon_data) 
    or (not moon_data.home_page_data) 
    or (not moon_data.home_page_data.select_rewards_status) then 
        return t_retCode.n_WORK_ERR, '[ERROR] moon_set_select_rewards no moon_data!'
    end

    --可领奖且已设置了领奖ID此时就不能更换奖励了
    if moon_data.home_page_data.select_rewards_status==mis_tools.REWARDS_STATUS.READY 
    and moon_data.home_page_data.select_rewards_id then 
        return t_retCode.n_WORK_ERR, '[ERROR] moon_set_select_rewards can not change rewards!'
    end

    moon_data.home_page_data.select_rewards_id = select_id

    local n_code, _desc = mis_data.get_user():set_moon_data(moon_data)
    if n_code ~= t_retCode.n_OK then
        log.day_list(LOG_NAME, "[ERROR] moon_set_select_rewards", "set_moon_data error!", "uin="..uin)
        return n_code, _desc
    end

    return t_retCode.n_OK
end

--领取自选大奖
--参数： 
    --无
--返回值： 
   --成功：0   失败：非0
   --发的具体奖品信息
M.moon_get_select_rewards = function ()
    local uin =  tonumber(ngx.ctx.m_params.uin)
    local apiid = tonumber(ngx.ctx.m_params.apiid)
    local t_moonConf 	= mis_data.t_moon.t_conf 

    local ok, moon_data = mis_data.get_user():get_moon_data()
    if ok~=t_retCode.n_OK then
        return t_retCode.n_SYS_ERR, 'ssdb error'
    end

    if not uin or (not apiid) or (not t_moonConf) 
    or (not t_moonConf.wishing_cfg) 
    or (not t_moonConf.wishing_cfg.select_list) then 
        return t_retCode.n_PARAM_ERR, 'param error'
    end

    if (not moon_data) 
    or (not moon_data.home_page_data) 
    or (not moon_data.home_page_data.select_rewards_status) 
    or (not moon_data.home_page_data.select_rewards_id) then 
        return t_retCode.n_WORK_ERR, '[ERROR] moon_get_select_rewards no moon_data!'
    end

    --还不能领奖
    if moon_data.home_page_data.select_rewards_status~=mis_tools.REWARDS_STATUS.READY then 
        return t_retCode.n_WORK_ERR, '[ERROR] moon_get_select_rewards no rewards!'
    end

    local t_ret = {}
    local select_id = tonumber(moon_data.home_page_data.select_rewards_id)
    t_ret.id  = tonumber(t_moonConf.wishing_cfg.select_list[select_id].awardId)
    t_ret.num  = tonumber(t_moonConf.wishing_cfg.select_list[select_id].awardNum)

    --发给账号服需要这种结构
    local send_rewards = {}
    table.insert(send_rewards, t_ret)
    --账号服发奖
    local ok2, reason_1, s_items, s_reason = mis_bridge.add_items(uin, send_rewards, "mis_sanrio", "mis_sanrio_add_item")
    if ok2~=t_retCode.n_OK then 
        log.day_list(LOG_NAME, '[ERROR] moon_get_select_rewards call accout error!', "uin="..uin, "apiid="..apiid, "send_rewards="..uu.to_str(send_rewards)
            ,"accout_ret="..uu.to_str(ok2), "reason_1="..reason_1, "s_items="..uu.to_str(s_items), "s_reason="..s_reason)
        return t_retCode.n_SYS_ERR, "call account add_items error!"
    end

    --账号服成功发奖后自选大奖复位
    moon_data.home_page_data.location_status = {0, 0, 0, 0, 0, 0, 0, 0, 0}
    moon_data.home_page_data.rewards_status = {0, 0, 0, 0, 0, 0, 0}
    moon_data.home_page_data.round = moon_data.home_page_data.round + 1
    moon_data.home_page_data.select_rewards_id = nil
    moon_data.home_page_data.select_rewards_status = mis_tools.REWARDS_STATUS.NONE

    if not moon_data.already_select_items then 
        moon_data.already_select_items = {}
    end 
    table.insert(moon_data.already_select_items, select_id)

    local n_code, _desc = mis_data.get_user():set_moon_data(moon_data)
    if n_code ~= t_retCode.n_OK then
        log.day_list(LOG_NAME, "[ERROR] moon_get_select_rewards", "set_moon_data error!", "uin="..uin)
        return n_code, _desc
    end

    --埋点数据
    mis_log.remote_pure_day("autumnfestival_receive", mis_common.table_to_json({
        ip = ngx.ctx.m_params.s_remoteAddr or ngx.ctx.xff or ngx.var.remote_addr or "nil",
        uin = uin,
        time = ngx.ctx.m_params.createTime or uu.now(),
        country = ngx.ctx.m_params.country or 'nil',
        apiid = ngx.ctx.m_params.apiid or 'nil',
        ver = ngx.ctx.m_params.ver or 'nil',
        lang = ngx.ctx.m_params.lang or 'nil',

        key = 'getaward',
        type = "autumnfestival_receive",
        bonus = send_rewards,
    }))

    --log.day_list(LOG_NAME, '[INFO] moon_get_select_rewards ok', 'uin='..uin, "apiids="..apiid
    --    , "rewards="..uu.to_str(send_rewards)
    --)

    return t_retCode.n_OK, t_ret
end

--获取月饼界面
--参数： 无
--返回值：
    --task_list字段数据同三丽鸥字段含义
M.moon_task_status = function ()
    local uin =  tonumber(ngx.ctx.m_params.uin)
    local apiid = tonumber(ngx.ctx.m_params.apiid)
    local t_moonConf = mis_data.t_moon.t_conf 
    --log.debug("t_moonConf="..uu.to_str(t_moonConf))

    if (not uin) or (not apiid) or (not t_moonConf) 
    or (not t_moonConf.task_cfg) then 
        return t_retCode.n_PARAM_ERR, 'param error'
    end

    local ok, moon_data = mis_data.get_user():get_moon_data()
    if ok~=t_retCode.n_OK then
        return t_retCode.n_SYS_ERR, 'ssdb error'
    end
    if not moon_data then 
        moon_data = {}
        moon_data.task_data = {}
    end
    if not moon_data.task_data then 
        moon_data.task_data = {}
    end

    --
    mis_tools.update_task_info(uin, t_moonConf.task_cfg, moon_data.task_data)

    local n_code, _desc = mis_data.get_user():set_moon_data(moon_data)
    if n_code ~= t_retCode.n_OK then
        log.day_list(LOG_NAME, "[ERROR] moon_task_status", "set_moon_data error!", "uin="..uin)
        return n_code, _desc
    end

    --这里月饼总数是在moon_data.total_score里
    moon_data.task_data.total_score = moon_data.total_score

    return  t_retCode.n_OK, moon_data.task_data
end

--领取月饼任务积分
--参数： task_id 领取奖励的任务ID
--返回值：
    --num 数量
    --itemId 物品ID
M.moon_get_task_rewards = function ()
    local uin =  tonumber(ngx.ctx.m_params.uin)
    local apiid = tonumber(ngx.ctx.m_params.apiid)
    if (not uin) or (not apiid) then 
        return t_retCode.n_PARAM_ERR, 'param error'
    end

    local task_id = tonumber(ngx.ctx.m_params.task_id)
    if not task_id then
        return t_retCode.n_PARAM_ERR, 'param error'
    end

    local ok, moon_data = mis_data.get_user():get_moon_data()
    if ok~=t_retCode.n_OK then
        return t_retCode.n_SYS_ERR, 'ssdb error'
    end
    if (not moon_data) 
    or (not moon_data.total_score)
    or (not moon_data.task_data) 
    or (not moon_data.task_data.task_list) 
    or (not moon_data.task_data.task_list[task_id]) 
    or (not moon_data.task_data.task_list[task_id].bonus)
    or (not moon_data.task_data.task_list[task_id].bonus.num) 
    or (not tonumber(moon_data.task_data.task_list[task_id].bonus.num)) then 
        return t_retCode.n_WORK_ERR, '[ERROR] moon_get_task_rewards no moon_data!'
    end

    if moon_data.task_data.task_list[task_id].status ~= mis_tools.REWARDS_STATUS.READY then 
        return t_retCode.n_WORK_ERR, '[ERROR] moon_get_task_rewards not ready!'
    end

    local task_data = moon_data.task_data
    task_data.task_list[task_id].status = mis_tools.REWARDS_STATUS.ALREADY
    moon_data.task_data.total_score = moon_data.task_data.total_score + tonumber(moon_data.task_data.task_list[task_id].bonus.num)  
    --这个才是真正用来点亮九宫格的月饼数，上面那个纯粹是任务完成积分
    moon_data.total_score = moon_data.total_score + tonumber(moon_data.task_data.task_list[task_id].bonus.num)

    local n_code, _desc = mis_data.get_user():set_moon_data(moon_data)
    if n_code ~= t_retCode.n_OK then
        log.day_list(LOG_NAME, "[ERROR] moon_get_task_rewards", "set_moon_data error!", "uin="..uin)
        return n_code, _desc
    end

    log.day_list(LOG_NAME, '[INFO] moon_get_task_rewards ok', 'uin='..uin, "apiids="..apiid
        , "add_score="..tonumber(moon_data.task_data.task_list[task_id].bonus.num)
        , "total_score="..moon_data.total_score, "task_data.score="..moon_data.task_data.total_score
        , "now_time="..uu.now()
    )

    return  t_retCode.n_OK, task_data.task_list[task_id].bonus
end

--迷你币购买月饼
--参数： gift_id 礼盒ID
--返回值：
    --成功0 失败非0 
    --目前总月饼数
M.moon_buy_cake = function ()
    local uin =  tonumber(ngx.ctx.m_params.uin)
    local apiid = tonumber(ngx.ctx.m_params.apiid)
    if (not uin) or (not apiid) then 
        return t_retCode.n_PARAM_ERR, 'param error'
    end
    local t_moonConf 	= mis_data.t_moon.t_conf 
    local gift_id = tonumber(ngx.ctx.m_params.gift_id)

    if not gift_id or not uin or not apiid
    or (not t_moonConf.task_cfg) 
    or (not t_moonConf.task_cfg.gift_list) 
    or (not t_moonConf.task_cfg.gift_list[gift_id])
    or (not t_moonConf.task_cfg.gift_list[gift_id].cakeNum)
    or (not t_moonConf.task_cfg.gift_list[gift_id].giftPrice) 
    or (not tonumber(t_moonConf.task_cfg.gift_list[gift_id].cakeNum))
    or (not tonumber(t_moonConf.task_cfg.gift_list[gift_id].giftPrice)) then 
        return t_retCode.n_SYS_ERR, 'param error1'
    end

    local ok, moon_data = mis_data.get_user():get_moon_data()
    if ok~=t_retCode.n_OK then
        return t_retCode.n_SYS_ERR, 'ssdb error'
    end
    if (not moon_data) 
    or (not moon_data.total_score) 
    or (not tonumber(moon_data.total_score)) then 
        return t_retCode.n_WORK_ERR, '[ERROR] moon_buy_cake no moon_data!'
    end

    local gift_info = t_moonConf.task_cfg.gift_list[gift_id]
    local cost_coins = tonumber(gift_info.giftPrice) 
    local cakeNum = tonumber(gift_info.cakeNum) 

    if (cost_coins<=0) or (cakeNum<=0) then 
        return t_retCode.n_SYS_ERR, 'param error2'
    end
    --log.debug("gift_info="..uu.to_str(gift_info))
    
    --update_task
    if not moon_data.task_data then 
        moon_data.task_data = {}
    end
    mis_tools.update_task(1004, 1, moon_data.task_data, t_moonConf.task_cfg)

    --账号服迷你币 --id=2代表买月饼礼盒
    local ext = mis_common.table_to_json({name = 'sanrio_buy_skin', now = uu.now(), items={id=2, price=cost_coins, num=cakeNum} })
	local s_code, s_desc = mis_bridge.cost_money(uin, nil, cost_coins, mis_config.t_costType.n_COIN, 'sanrio_buy_skin', ext)
    if not s_code or s_code~=t_retCode.n_OK then 
        log.day_list(LOG_NAME, '[ERROR] moon_buy_cake cost_money error!', 'uin='..uin, 'apiid='..apiid, 'ext='..uu.to_str(ext)
            ," code="..s_code, "s_desc="..(s_desc or "nil"))
        return t_retCode.n_SYS_ERR, "call account cost_money error!"
    end

    moon_data.total_score = moon_data.total_score + cakeNum

    local n_code, _desc = mis_data.get_user():set_moon_data(moon_data)
    if n_code ~= t_retCode.n_OK then
        log.day_list(LOG_NAME, "[ERROR] moon_buy_cake", "set_moon_data error!", "uin="..uin)
        return n_code, _desc
    end

    --埋点数据
    mis_log.remote_pure_day("autumnfestival_buy_mooncake", mis_common.table_to_json({
        ip = ngx.ctx.m_params.s_remoteAddr or ngx.ctx.xff or ngx.var.remote_addr or "nil",
        uin = uin,
        time = ngx.ctx.m_params.createTime or uu.now(),
        country = ngx.ctx.m_params.country or 'nil',
        apiid = ngx.ctx.m_params.apiid or 'nil',
        ver = ngx.ctx.m_params.ver or 'nil',
        lang = ngx.ctx.m_params.lang or 'nil',

        key = 'finish',
        type = "autumnfestival_buy_mooncake",
        point = cost_coins,
        add_mooncake_num = cakeNum,
    }))

    return  t_retCode.n_OK, cakeNum 
end

--中秋活动上报完成某个任务
--参数: 
    --times：完成次数 [每日登录X分钟，就需要上报X，如5分钟就传5；]
    --event:事件类型：该任务配置表上的event类型
--返回值：0 or 错误码
M.moon_finsh_task = function ()
    local apiid = tonumber(ngx.ctx.m_params.apiid)
    local uin =  tonumber(ngx.ctx.m_params.uin)
    local event = tonumber(ngx.ctx.m_params.event)
    local times = tonumber(ngx.ctx.m_params.times)
    local t_moonConf 	= mis_data.t_moon.t_conf
    
    if (not apiid) or (not event) or (not times) or (not uin) or (not t_moonConf) then 
		return t_retCode.n_PARAM_ERR, 'param error'
	end

    local ok, moon_data = mis_data.get_user():get_moon_data()
    if ok~=t_retCode.n_OK then
        return t_retCode.n_SYS_ERR, 'ssdb error'
    end

    if not moon_data then 
        moon_data = {}
        moon_data.task_data = {}
    end
    if not moon_data.task_data then 
        moon_data.task_data = {}
    end
    local ok2, rewards = mis_tools.update_task(event, times, moon_data.task_data, t_moonConf.task_cfg)
    if not ok2 then 
        log.day_list(LOG_NAME, "[ERROR] moon_finsh_task", "task not finish!", "uin="..uin)
        return t_retCode.n_WORK_ERR, 'update_task error--->task not finish!'
    end

    local n_code, n_desc = mis_data.get_user():set_moon_data(moon_data)
    if n_code ~= t_retCode.n_OK then
        log.day_list(LOG_NAME, "[ERROR] moon_finsh_task", "set_moon_data error!")
        return n_code, n_desc
    end

    --[[
    log.day_list(LOG_NAME, '[INFO] moon_finsh_task', "apiid="..apiid, 'uin='..uin, "ver="..(ngx.ctx.m_params.ver or 'nil')
        , 'times='..times, 'event='..event
        , 'rewards='..uu.to_str(rewards), '[not add now!]now total_score='..moon_data.total_score
        , 'event_times_data='..moon_data.events_finish_times[event])
    --]]

    return t_retCode.n_OK, rewards
end

--查玩家商业化道具
M.moon_query_items = function ()
    local uin =  tonumber(ngx.ctx.m_params.uin)
    local apiid = tonumber(ngx.ctx.m_params.apiid)
    if (not uin) or (not apiid) then 
        return t_retCode.n_PARAM_ERR, 'param error'
    end
    
    --皮肤
    local skin_list = mis_tools.query_skin_account(uin)
    --仓库道具
    local items = mis_tools.query_account_items(uin)
    --头像框
    local head_frames = mis_tools.query_profile_head_frame(uin)
    --avt
    local avt = mis_tools.query_owned_avatar_account(uin)
    --坐骑
    local mount = mis_tools.query_owned_mount_account(uin)
    --武器
    local wepon = mis_tools.query_all_weponskins(uin)
    --喷漆
    local paints = mis_tools.query_all_spraypaints(uin)

    log.debug("--------------------------------------皮肤表-----------------------------------------------------")
    log.debug("skin_list="..uu.to_str(skin_list))
    log.debug("--------------------------------------物品表-----------------------------------------------------")
    log.debug("items="..uu.to_str(items))
    log.debug("--------------------------------------永久头像框-----------------------------------------------------")
    log.debug("head_frame="..uu.to_str(head_frames))
    log.debug("--------------------------------------avt-----------------------------------------------------")
    log.debug("avt="..uu.to_str(avt))
    log.debug("--------------------------------------坐骑-----------------------------------------------------")
    log.debug("mount="..uu.to_str(mount))
    log.debug("--------------------------------------武器-----------------------------------------------------")
    log.debug("wepon="..uu.to_str(wepon))
    log.debug("--------------------------------------喷漆-----------------------------------------------------")
    log.debug("paints="..uu.to_str(paints))

    --log.debug("--------------------------------------修改物品-----------------------------------------------------")
    --[[
    --发给账号服需要这种结构
    local send_rewards = {}
    local t1 = {id=10002, num=1000000}
    local t2 = {id=10009, num=1000000}
    table.insert(send_rewards, t1)
    table.insert(send_rewards, t2)
    --账号服发奖
    mis_bridge.add_items(uin, send_rewards, "test", "test")
    --]]

end


M.moon_query_ItemUseSkinDef = function ()
	local t_item_use_skin_def_config = mis_data.t_item_use_skin_def_config.t_conf 
	if (not t_item_use_skin_def_config) then 
		log.debug( "[ERROR] item_to_skin config is nil!")
	end

	log.debug("t_item_use_skin_def_config="..uu.to_str(t_item_use_skin_def_config))

end


----------------------------------------------------------------

local function add_moon_cake(t_moonData,num)
    if t_moonData.total_score and num then
        t_moonData.total_score = t_moonData.total_score + num
        return t_moonData.total_score
    end

    return 0
end

-- 说明：中秋moon 业务前置检测
-- 返回：n                 状态码
--      ts                  描述
M.pre_moon = function()
    local apiid = tonumber(ngx.ctx.m_params.apiid)
    local ver = ngx.ctx.m_params.ver
    local t_moonConf = mis_data.t_moon.t_conf 
    local no_check = ngx.ctx.m_params.no_check
    if no_check and (no_check == "query_no_check") then 
        return t_retCode.n_OK
    end

    local _check, _info = mis_tools.check_limit(t_moonConf, apiid, ver)
    if not _check then 
        return t_retCode.n_AUTH_ERR, _info
    end

    return t_retCode.n_OK
end

--拉取用户数据
M.moon_get_user_status = function ()
    local _desc,s_desc
    local t_params          = ngx.ctx.t_params
    local uin = t_params.uin
    local t_user = mis_data.get_user()
    local n_code, t_moonData = t_user:get_moon_data()
    if n_code ~= t_retCode.n_OK or t_moonData== nil then
        log.day_list("fuckmoon","moon_get_user_status-flag-1",ngx.ctx.t_params.uin,uu.to_str(n_code),uu.to_str(t_moonData))
        return n_code, t_moonData
    end

    local n_now = uu.now()

    --获取最新配置
    local conf  = mis_data.t_moon.t_conf 

    --如果没有月饼的信息，则生成一个
    if t_moonData.total_score == nil then
        t_moonData.total_score = 0
        --log.day_list("fuckmoon","moon_get_user_status-flag-1-2",ngx.ctx.t_params.uin,uu.to_str(t_moonData))
    end

    --如果没有相关绑定手机的信息，则生成一个
    if t_moonData.bind_phone_status == nil then
        t_moonData.bind_phone_status = 0 --0,未绑定  1,已绑定,未领取奖励  2,已绑定，已领取
        --log.day_list("fuckmoon","moon_get_user_status-flag-2",ngx.ctx.t_params.uin,uu.to_str(t_moonData))
    end

    if t_moonData.bind_phone_status == 0 then
        --log.day_list("fuckmoon","moon_get_user_status-flag-3",ngx.ctx.t_params.uin,uu.to_str(t_moonData))
        if mis_bridge.query_bind_phone(uin) then
            --log.day_list("fuckmoon","moon_get_user_status-flag-4",ngx.ctx.t_params.uin,uu.to_str(t_moonData))
            t_moonData.bind_phone_status = 1
        end

    end

    if t_moonData.moon_vip == nil or t_moonData.moon_vip == 0 then
        t_moonData.moon_vip = 0
        --log.day_list("fuckmoon","moon_get_user_status-flag-4-1",ngx.ctx.t_params.uin,uu.to_str(t_moonData))
        --如果不是Vip就尝试去拉取下数据
        local ret, is_vip = mis_bridge.query_mini_vip(ngx.ctx.t_params.uin)
        if ret and is_vip then
            t_moonData.moon_vip = 1 --可领
            --log.day_list("fuckmoon","moon_get_user_status-flag-4-2",ngx.ctx.t_params.uin,uu.to_str(t_moonData))
        end
    end

    --判断每日刷新功能
    local now_day = tonumber(os.date("%Y%m%d", os.time()))
    if t_moonData.day_flag == nil then
        t_moonData.day_flag = now_day
    end

    if t_moonData.day_flag ~= now_day then
        --刷新每日
        t_moonData.day_flag = now_day

        --判断每日会员领取月饼
        --且是会员且领过了，才刷新重置
        if t_moonData.moon_vip == 2 then
            --log.day_list("fuckmoon","moon_get_user_status-flag-4-3",ngx.ctx.t_params.uin,uu.to_str(t_moonData))
            t_moonData.moon_vip = 1
        end

    end
    
    n_code, _desc = t_user:set_moon_data(t_moonData)
   
    if n_code ~= t_retCode.n_OK then
        log.day_list("fuckmoon","moon_get_user_status-flag-5",ngx.ctx.t_params.uin,uu.to_str(n_code),uu.to_str(_desc),uu.to_str(t_moonData))
        return n_code, _desc
    end
    local data = {}
    data.bind_phone_award_num = conf.wishing_cfg.bind_phone_award_num
    data.vip_day_award_num = conf.wishing_cfg.vip_day_award_num
    data.moon_vip=t_moonData.moon_vip
    data.bind_phone_status=t_moonData.bind_phone_status
    data.total_score=t_moonData.total_score
    --log.day_list("fuckmoon","moon_get_user_status-flag-6",ngx.ctx.t_params.uin,uu.to_str(data))
    return t_retCode.n_OK, {data = data}

end

--领取绑定手机用户的月饼
M.moon_get_user_mooncake_phone = function ()
    local _desc,s_desc
    local t_params          = ngx.ctx.t_params
    local uin = t_params.uin
    local t_user = mis_data.get_user()
    local n_code, t_moonData = t_user:get_moon_data()
    if n_code ~= t_retCode.n_OK or t_moonData== nil then
        log.day_list("fuckmoon","moon_get_user_mooncake_phone-flag-1",ngx.ctx.t_params.uin,uu.to_str(n_code),uu.to_str(t_moonData))
        return n_code, t_moonData
    end

    --未绑定用户
    if t_moonData.bind_phone_status == nil or t_moonData.bind_phone_status == 0 then

        --再判断一次是否绑定了
        if mis_bridge.query_bind_phone(uin) then
            t_moonData.bind_phone_status = 1
        else
            --log.day_list("fuckmoon","moon_get_user_mooncake_phone-flag-2",ngx.ctx.t_params.uin,uu.to_str(t_moonData.bind_phone_status))
            return t_retCode.n_NO_DATA, "not bind phone"
        end

    end

    --已绑定且已领取了
    if t_moonData.bind_phone_status == 2 then
        log.day_list("fuckmoon","moon_get_user_mooncake_phone-flag-3",ngx.ctx.t_params.uin,uu.to_str(t_moonData.bind_phone_status))
        return t_retCode.n_NO_DATA, "bind phone is haved"
    end
    --获取最新配置
    local t_moonConf  =  mis_data.t_moon.t_conf 
    local bind_phone_award_num = t_moonConf.wishing_cfg.bind_phone_award_num
    t_moonData.bind_phone_status = 2
     
    local ret_num = add_moon_cake(t_moonData, bind_phone_award_num)

    n_code, _desc = t_user:set_moon_data(t_moonData)
   
    if n_code ~= t_retCode.n_OK then
        log.day_list("fuckmoon","moon_get_user_mooncake_phone-flag-4",ngx.ctx.t_params.uin,uu.to_str(n_code),uu.to_str(_desc),uu.to_str(t_moonData))
        return n_code, _desc
    end
    local bonus = {itemId=666666,num=bind_phone_award_num}
    --log.day_list("fuckmoon","moon_get_user_mooncake_phone-flag-5",ngx.ctx.t_params.uin,uu.to_str(t_moonData),bind_phone_award_num)
    return t_retCode.n_OK, bonus

end

--会员领取每日月饼
M.moon_get_user_mooncake_vip_day= function ()
    local _desc,s_desc
    local t_params          = ngx.ctx.t_params
    local uin = t_params.uin
    local t_user = mis_data.get_user()
    local n_code, t_moonData = t_user:get_moon_data()
    if n_code ~= t_retCode.n_OK or t_moonData== nil then
        log.day_list("fuckmoon","moon_get_user_mooncake_vip_day-flag-1",ngx.ctx.t_params.uin,uu.to_str(n_code),uu.to_str(t_moonData))
        return n_code, t_moonData
    end

    if t_moonData.moon_vip ~= 1 then
        log.day_list("fuckmoon","moon_get_user_mooncake_vip_day-flag-2",ngx.ctx.t_params.uin,uu.to_str(t_moonData.moon_vip))
        return t_retCode.n_NO_DATA, "user is not vip"
    end

    t_moonData.moon_vip = 2 --设为已领取
    --获取最新配置
    local t_moonConf  =  mis_data.t_moon.t_conf 
    local vip_day_award_num = t_moonConf.wishing_cfg.vip_day_award_num

    local ret_num = add_moon_cake(t_moonData, vip_day_award_num)

    n_code, _desc = t_user:set_moon_data(t_moonData)
   
    if n_code ~= t_retCode.n_OK then
        log.day_list("fuckmoon","moon_get_user_mooncake_vip_day-flag-3",ngx.ctx.t_params.uin,uu.to_str(n_code),uu.to_str(_desc),uu.to_str(t_moonData))
        return n_code, _desc
    end
    local bonus = {itemId=666666,num=vip_day_award_num}
    --log.day_list("fuckmoon","moon_get_user_mooncake_vip_day-flag-4",ngx.ctx.t_params.uin,uu.to_str(t_moonData), vip_day_award_num)
    return t_retCode.n_OK, bonus
end

return M

